package controllers
{
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	
	import models.ConfigModel;
	import models.LocalSetting;
	
	import mx.controls.Alert;
	
	import views.GameWindow;
	import views.GamesRenderer;

	public class ApplicationController
	{
		[DexterBinding]
		public var configModel:ConfigModel;
		[DexterBinding]
		public var localSetting:LocalSetting;
		[DexterEvent]
		public function appStart():void{
			configModel.loadConfig();
		}
		[DexterEvent]
		public function configComplete():void{
			
		}
		[DexterEvent]
		public function startUpGame(src:String):void{
			var file:File = File.applicationStorageDirectory.resolvePath(src);
			var fileStream:FileStream = new FileStream();
			var fileData:ByteArray = new ByteArray();
			fileStream.open(file, FileMode.READ);
			fileStream.readBytes(fileData,0,file.size);
			fileStream.close();
			GameWindow.show().loadGame(src,fileData);
		}
		[DexterEvent]
		public function deleteGame(src:String):void{
			var file:File = File.applicationStorageDirectory.resolvePath(src);
			file.deleteFile();
		}
		[DexterEvent]
		public function downloadGame(src:String,ref:GamesRenderer = null):void{
			var file:File = File.applicationStorageDirectory.resolvePath(src);
			var gameLoader:URLStream = new URLStream();
			if(ref)ref.progressBar.source = gameLoader;
			var onLoaded:Function = function(event:Event):void{
				gameLoader.removeEventListener(Event.COMPLETE,onLoaded);
				var fileData:ByteArray = new ByteArray();
				gameLoader.readBytes(fileData, 0, gameLoader.bytesAvailable);
				var fileStream:FileStream = new FileStream();
				fileStream.open(file, FileMode.WRITE);
				fileStream.writeBytes(fileData, 0, fileData.length);
				fileStream.close();
				if(ref)ref.downloadComplete();
				else sendDexterEvent("updateGameComplete",src);
			}
			gameLoader.addEventListener(Event.COMPLETE,onLoaded,false,0,true);
			gameLoader.addEventListener(IOErrorEvent.IO_ERROR,Alert.show,false,0,true);
			gameLoader.load(new URLRequest(configModel.baseURL + src));
		}
	}
}